/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.util.LinkedList;
import java.util.Scanner;
import util.LispFileReader;
import util.LispFileWriter;
import util.Movement;

/**
 *
 * @author comercio
 */
public class Puzzle8SolverModel extends AbstractModel {

    private LispFileReader reader;
    private LispFileWriter writer;
    private Long timeSpent;
    private int numberOfMovementsOfSolution;

    public Puzzle8SolverModel() {
        reader = new LispFileReader();
        writer = new LispFileWriter();
    }

    public LinkedList<Movement> solve(Puzzle8Model puzzle) {
        long start = System.currentTimeMillis();
        long timeElapsed=0;
        String write = puzzle.toLispCompatible();
        writer.writeOut(write);
        try {
            //TODO Lisp Processing
            //Process p = Runtime.getRuntime().exec("cmd.exe /c \"C:\\112796\\puzzle8\\trunk\\Puzzle8\\lispBat.bat\"");
            //Process p = Runtime.getRuntime().exec("cmd /c \".\\LISP\\MULISP.com .\\LISP\\puzz8\"");
            Process p = Runtime.getRuntime().exec("cmd /c lispBat");
//            Scanner sc = new Scanner(p.getInputStream());
//            while(sc.hasNext())
//                System.out.println(sc.next());
            System.out.println("Proceso inicializado con éxito");
            
            while(p.waitFor() !=0 && timeElapsed<20000 ){
                timeElapsed = System.currentTimeMillis() - start;
            }
            p.destroy();
            //p.waitFor();
            System.out.println("Prcoeso terminado");
        } catch (Exception ex) {
            System.err.println(ex);
        }
        LinkedList<Movement> movements = reader.readFile();
        timeElapsed = System.currentTimeMillis() - start;
        firePropertyChange("TimeSpent", new Long(0), new Long(timeElapsed));
        timeSpent = timeElapsed;
        firePropertyChange("NumberOfMovementsOfSolution", new Integer(numberOfMovementsOfSolution), new Integer(movements.size()));
        numberOfMovementsOfSolution = movements.size();
        
        return movements;
    }
}
